package com.suyunyou.manager.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.suyunyou.manager.dao.SpiderSiteDao;
import com.suyunyou.manager.enums.SpiderSiteType;
import com.suyunyou.manager.pojo.SpiderSite;
import com.system.comm.model.KvEntity;

/**
 * 提取网站的Service
 * @author yuejing
 * @date 2016年6月26日 上午8:31:45
 * @version V1.0.0
 */
@Component
public class SpiderSiteService {

	@Autowired
	private SpiderSiteDao spiderSiteDao;
	@Autowired
	private SpiderLinkService spiderLinkService;
	/*@Autowired
	private SpiderSiteCache spiderSiteCache;*/
	
	/**
	 * 保存提取网站
	 * @param spiderSite
	 */
	public void saveOrUpdate(SpiderSite spiderSite) {
		SpiderSite org = get(spiderSite.getSiteId());
		if(org == null) {
			spiderSiteDao.save(spiderSite);
		} else {
			spiderSiteDao.update(spiderSite);
			if (!spiderSite.getDomain().equals(org.getDomain())) {
				// 域名发生变更
				spiderLinkService.updateDomainBySiteId(spiderSite.getSiteId(), spiderSite.getDomain());
			}
			//spiderSiteCache.del(spiderSite.getSiteId());
		}
	}

	/**
	 * 根据编号获取对象
	 * @param siteId
	 * @return
	 */
	public SpiderSite get(Integer siteId) {
		return spiderSiteDao.get(siteId);
	}

	/**
	 * 获取所有提起的网站
	 * @return
	 */
	public List<SpiderSite> findAll() {
		List<SpiderSite> list = spiderSiteDao.findAll();
		for (SpiderSite spiderSite : list) {
			spiderSite.setTypeName(SpiderSiteType.getText(spiderSite.getType()));
		}
		return list;
	}

	/**
	 * 删除网站
	 * @param siteId
	 */
	public void delete(Integer siteId) {
		spiderSiteDao.delete(siteId);
		//spiderSiteCache.del(siteId);
	}

	/**
	 * 获取启用的网站
	 * @return
	 */
	public List<SpiderSite> findEnable() {
		return spiderSiteDao.findEnable();
	}

	public List<KvEntity> findKvAll() {
		List<KvEntity> data = new ArrayList<KvEntity>();
		List<SpiderSite> list = findAll();
		for (SpiderSite spiderSite : list) {
			data.add(new KvEntity(spiderSite.getSiteId().toString(), spiderSite.getName()));
		}
		return data;
	}

	public void updateRuleTime(Integer siteId, Date ruleTime) {
		spiderSiteDao.updateRuleTime(siteId, ruleTime);
	}

}